package com.lik888.web1.controller;

import com.github.benmanes.caffeine.cache.Cache;
import com.lik888.web1.Log.LookLog;
import com.lik888.web1.entity.DTO.GoodsTypePageDTO;
import com.lik888.web1.entity.GoodsTable;
import com.lik888.web1.entity.R;
import com.lik888.web1.entity.DTO.PageDTO;
import com.lik888.web1.entity.VO.PageVo;
import com.lik888.web1.service.IGoodsTableService;
import com.lik888.web1.utils.AliOssUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2025-11-05
 */
@RestController
@RequestMapping("/goods")
@RequiredArgsConstructor
@EnableAspectJAutoProxy(exposeProxy = true)

public class GoodsTableController {
  private final AliOssUtil aliOssUtil;
  private final IGoodsTableService goodsTableService;
  private final Cache<String, Object> caffeineCache;
    //OSS
    // 上传商品标题图片
    @PostMapping("/uploadtitleimg")
    @PreAuthorize("hasAuthority('manager')")
    public R<String> upload(@RequestParam("file") MultipartFile file) throws IOException {
        //原始文件名
        String originalFilename = file.getOriginalFilename();
        //截取原始文件名的后缀   dfdfdf.png
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        //构造新文件名称
        String objectName = UUID.randomUUID().toString() + extension;
        //文件的请求路径
        String filePath = aliOssUtil.upload(file.getBytes(), objectName);
        return R.ok(filePath);
    }

    // 上传商品详情图片
    @PostMapping("/uploadimgs")
    @PreAuthorize("hasAuthority('manager')")
    public R<List<String>> uploadMultiple(
            @RequestParam("files") MultipartFile[] files) throws IOException {
        // 存储所有图片的OSS路径
        List<String> filePaths = new ArrayList<>();
        // 循环处理每个文件 增强FOR循环
        for (MultipartFile file : files) {
            // 跳过空文件（防止前端误传）
            if (file.isEmpty()) {
                continue;
            }
            // 处理单个文件（逻辑与原来一致）
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String objectName = UUID.randomUUID().toString() + extension;
            String filePath = aliOssUtil.upload(file.getBytes(), objectName);
            // 添加到结果列表
            filePaths.add(filePath);
        }
        // 返回所有图片的路径
        return R.ok(filePaths);
    }


    // TODO Create Goods 创建商品 并将上传的图片保存到对应的商品数据库以及对应的图片详情数据库
    @PostMapping("/create")
    @PreAuthorize("hasAuthority('manager')")
    public R<GoodsTable> create(@RequestBody GoodsTable goodsTable,@RequestParam("goodsImgs") ArrayList<String> goodsImgs){
         R result = goodsTableService.CreateGoods(goodsTable,goodsImgs);
      return result;
    }

    // 查询商品类型
    @GetMapping("/type")
    @PreAuthorize("hasAuthority('default')")
     @LookLog(value = "查看商品类型")
    public R<List<String>> getType(){
         List<String> type = (List<String>) caffeineCache.get("type", type1 -> goodsTableService.SelectType());
        return R.ok(type);
    }

    // 查询商品详情
    @GetMapping("/detail")
    @PreAuthorize("hasAuthority('default')")
    public R<GoodsTable> getDetail(@RequestParam("id") Long id){
        GoodsTable detail = goodsTableService.getDetail(id);
//        GoodsTable goodsTable = (GoodsTable) caffeineCache.get("detail:" + id, id1 -> goodsTableService.getById(id));
        return R.ok(detail);
    }

    //商品上下架
    @PostMapping("/updown")
    @PreAuthorize("hasAuthority('manager')")
    public R<GoodsTable> upDown(@RequestParam("id") Long id,@RequestParam("status") Integer status){
        R result = goodsTableService.goodsUp(id,status);
        return result;
    }

    // 黑商品查询功能
    @GetMapping("/blacklist")
    @PreAuthorize("hasAuthority('default')")
    public R<String> getBlackList(String id){
        //线程休眠3秒
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            throw new RuntimeException("查询失败请稍后重试！");
        }

        return R.ok("这是一个绿色商品！请放心购买！");
    }

    //根据类型进行分页查询
    @GetMapping("/typepage")
    @PreAuthorize("hasAuthority('default')")
    public R<PageVo<GoodsTable>> getTypePage(@RequestBody GoodsTypePageDTO goodsTypePageDTO){
        PageVo<GoodsTable> pageVo = goodsTableService.getTypePage(goodsTypePageDTO);
        return R.ok(pageVo);
    }


    // 分页查询 TODO!
//    @GetMapping("/page")
//    @PreAuthorize("hasAuthority('default')")

}
